package cn.lau.platform.common.config;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;


@Configuration
public class HibernateConfig implements TransactionManagementConfigurer {


    @Resource(name="txManager")
    private PlatformTransactionManager txManager;


    @Bean
    public SessionFactory sessionFactory(@Qualifier("druidDataSource")DataSource dataSource){

        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setPackagesToScan("cn/lau/core/**/**/entity");
        return sessionFactoryBean.getObject();
    }

    //创建事务管理器
    @Bean(name = "txManager")
    public PlatformTransactionManager txManager(SessionFactory sessionFactory) {
        return new HibernateTransactionManager(sessionFactory);
    }

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager;
    }
}
